﻿using BLL;
using Model;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.其他窗体;
using 纺织贸易管理系统.其他窗体;
using 纺织贸易管理系统.新增窗体;
using 纺织贸易管理系统.设置窗体;
using 纺织贸易管理系统.选择窗体;

namespace 纺织贸易管理系统.报表窗体
{
    public partial class 客供底布入库 : Form
    {
        public DanjuTable  danju { get; set; }
        private List<danjumingxitable > danjumingxis = new List<danjumingxitable >();
        private DataTable FineCodeTable = new DataTable();
        private List<WarehousingDetailCode> detaicodelist = new List<WarehousingDetailCode>();
        public FormUseful Useful { get; set; }
        private int rowindex = 0;
        public 客供底布入库()
        {
            InitializeComponent();
            uiDatePicker1.Value = DateTime.Now;
            CreateGrid.Create(this.Name, gridView1);
            txtckmc.Text = QueryTime.DefaultStock;
            try
            {
                gridView1.Columns["Bianhao"].ColumnEdit = ButtonEdit1;
                gridView1.Columns["pingming"].ColumnEdit = ButtonEdit1;
                gridView1.Columns["danwei"].ColumnEdit = cmddanwei;
                gridView1.Columns["yanse"].ColumnEdit = colorbtn;
                gridView1.Columns["ColorNum"].ColumnEdit = colorbtn;
                gridView1.IndicatorWidth = 30;
            }
            catch
            {
                配置列ToolStripMenuItem_Click(null, null);
            }
        }
        private void Init()
        {
            if (Useful == FormUseful.新增)
            {
                danju = new DanjuTable();
                txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.生产入库单, uiDatePicker1.Value, DanjuLeiXing.入库单);
                txtkehu.Text = "";
                txtFahuodanwei.Text = string.Empty;
                txtbeizhu.Text = string.Empty;
                danjumingxis.Clear();
                for (int i = 0; i < 30; i++)
                {
                    danjumingxis.Add(new danjumingxitable() { danwei = "米" ,ganghao=string.Empty ,yanse =string.Empty ,houzhengli=string.Empty });
                }
                gridControl1.DataSource = danjumingxis;
                gridControl1.RefreshDataSource();
                uiDatePicker1.Value = DateTime.Now;
                uiDatePicker1.Enabled = true;
                cmbJincangyuanying.Text = "首次加工";
            }
            else
            {
                txtdanhao.Text = danju.dh;
                txtkehu.Text = danju.ksmc  ;
                uiDatePicker1.Value =danju.rq ;
                txtckmc.Text = danju.ckmc;
                txtbeizhu.Text = danju.bz;
                txtFahuodanwei.Text = danju.fromDanhao;
                uiDatePicker1.Enabled = false;
                cmbJincangyuanying.Text = danju.jiagongleixing;
                danjumingxis =danjumingxitableService.Getdanjumingxitablelst (x => x.danhao == danju.dh);
                detaicodelist = Connect.CreatConnect().Query<WarehousingDetailCode>(x => x.DocNum == txtdanhao.Text);
                for(int i=danjumingxis.Count;i<30;i++)
                {
                    danjumingxis.Add(new danjumingxitable() { danwei = "米", ganghao = string.Empty, yanse = string.Empty, houzhengli = string.Empty });
                }
                gridControl1.DataSource = danjumingxis;
                gridControl1.RefreshDataSource();
                if(Useful==FormUseful.查看 )
                {
                    新增ToolStripMenuItem.Enabled = false;
                }
            }
        }
        private void 新增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (uiDatePicker1.Value.ToShortDateString() != DateTime.Today.ToShortDateString())
            {
                if (MessageBox.Show("单据日期与系统日期不匹配？\r\n是否继续保存", this.Name, MessageBoxButtons.YesNo, MessageBoxIcon.Information) != DialogResult.Yes)
                {
                    return;
                }
            }
            //检查是否存在相同信息
            var mingxi = danjumingxis.Where(x => !string.IsNullOrEmpty(x.pingming)).ToList();
            foreach (var m in mingxi)
            {
                if (mingxi.Where(x => x.pingming == m.pingming && x.ganghao == m.ganghao&&x.yanse ==m.yanse ).Count() > 1)
                {
                    Tools.ShowMessageBox.ShowErrorBox($"存在重复信息！品名一样  缸号一样\r\n品名是:{m.pingming }\r\n缸号是:{m.ganghao }");
                    return;
                }
            }
            //检查是否有空缸号和空信息
            if (danjumingxis.Where(x => !string.IsNullOrEmpty(x.pingming) && string.IsNullOrEmpty(x.ganghao)).Count() > 0)
            {
                Sunny.UI.UIMessageBox.Show("存在空缸号记录，\r\n请检查输入的信息");
                return;
            }
            if (danjumingxis.Where(x => !string.IsNullOrEmpty(x.pingming) && x.chengpingmishu == 0).Count() > 0)
            {
                Sunny.UI.UIMessageBox.Show("存在0米数记录，\r\n请检查输入的信息");
                return;
            }
            if (danjumingxis.Where(x => !string.IsNullOrEmpty(x.pingming) && x.chengpingjuanshu == 0).Count() > 0)
            {
                Sunny.UI.UIMessageBox.Show("存在0卷数记录，\r\n请检查输入的信息");
                return;
            }
            //检查日期
            if (Useful == FormUseful.新增)
            {
                if (uiDatePicker1.Value.Date != DateTime.Now.Date)
                {
                    if (Sunny.UI.UIMessageBox.ShowAsk("单据日期与系统日期不相等！\r\n是否将单据日期调整为系统日期？"))
                    {
                        uiDatePicker1.Value = DateTime.Now;
                        txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.生产入库单, uiDatePicker1.Value, DanjuLeiXing.入库单);
                        foreach (var d in danjumingxis)
                        {
                            d.rq = uiDatePicker1.Value;
                            d.danhao = txtdanhao.Text;
                        }
                    }
                }
            }
            ///检查输入的客户是否存在客户资料中       
            var lianxiren = LXRService.GetOneLXR(x => x.MC == txtkehu.Text);
            if (string.IsNullOrWhiteSpace(lianxiren.MC))
            {
                Sunny.UI.UIMessageBox.Show($"该客户{txtkehu.Text}名称在客户资料中没有匹配到！\r\n请检查输入的客户名是否正确");
                return;
            }
            else
            {
                danju.ksbh = lianxiren.BH;
                if(QueryTime.IsMustNeedTel)
                {
                    if (string.IsNullOrEmpty (lianxiren.DH))
                    {
                        Tools.ShowMessageBox.ShowErrorBox("当前策略为客户必须要有联系电话！检测不到该客户的联系电话！");
                        return;
                    }
                }
            }
            ///
            if (string.IsNullOrWhiteSpace(txtFahuodanwei.Text))
            {
                UIMessageBox.ShowError("发货地址不能为空！\r\n请输入发货地址");
                return;
            }
            if (string.IsNullOrWhiteSpace(cmbJincangyuanying.Text))
            {
                UIMessageBox.ShowError("进仓原因不能为空！\r\n请选择进仓原因");
                return;
            }
            try
            {
               // Connect.dbcontext.BeginTran();
                gridView1.CloseEditor();
                if (danjumingxis.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList().Count == 0)
                {
                    Sunny.UI.UIMessageBox.ShowError("保存失败！没有任何布料！如果有布料品名必须要填写!");
                    return;
                }
                if (string.IsNullOrWhiteSpace(txtkehu.Text))
                {
                    Sunny.UI.UIMessageBox.ShowError("保存失败！请选择客户");
                    return;
                }
                if (string.IsNullOrWhiteSpace(txtckmc.Text))
                {
                    Sunny.UI.UIMessageBox.ShowError("保存失败！请选择仓库名称");
                    return;
                }
                danju.bz = txtbeizhu.Text;
                danju.ksmc = txtkehu.Text.TrimEnd(' ');
                danju.dh = txtdanhao.Text;
                danju.djlx = DanjuLeiXing.入库单;
                danju.rq = uiDatePicker1.Value;
                danju.ckmc = txtckmc.Text;
                danju.StockName = cmbcunfang.Text.TrimEnd(' ');
                danju.totaljuanshu = danjumingxis.Sum(x => x.chengpingjuanshu);
                danju.TotalMishu = danjumingxis.Sum(x => x.chengpingmishu);
                danju.zhuangtai = "未审核";
                danju.own = Tools.CurrentUser.user.YHBH;
                //进仓原因
                danju.jiagongleixing = cmbJincangyuanying.Text;
                ///fromDanhao就是真实的发货地址
                danju.fromDanhao = txtFahuodanwei.Text;
                foreach (var m in danjumingxis.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList())
                {
                    m.danhao = danju.dh;
                    m.CustomName = danju.ksmc;
                    m.rkdh = danju.dh;
                    m.InventoryQuantity = m.chengpingmishu;
                    m.suolv = 0;
                }
                if (Useful == FormUseful.新增)
                {
                    danju.dh = 单据BLL.检查单号(danju.dh);

                    if (!CheckStockBLL.CheckStock(danjumingxis.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList()))
                    {
                        return;
                    }
                    Connect.dbcontext.Insertable(danjumingxis.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList()).ExecuteCommand();
                    if (SysInfo.GetInfo.own != "审核制")
                    {
                        danju.zhuangtai = "已审核";
                    }
                    else
                    {
                        danju.zhuangtai = "未审核";
                    }
                    Connect.dbcontext.Insertable( danju).ExecuteCommand ();
                    生产入库单BLL.保存(danju, danjumingxis.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList());
                }
                else
                {
                    生产入库单BLL.修改单据(danju, danjumingxis);
                    var dt = Connect.dbcontext.Ado.SqlQuery<JuanHaoTable>($"select * from juanhaotable where ckmc in (select convert(nvarchar(200),id) from stocktable where rkdh='{danju.dh}')");
                    if (dt.Count > 0)
                    {
                        if (Sunny.UI.UIMessageBox.ShowAsk("该入库单已经有布料打卷检验了？是否继续修改保存"))
                        {
                            //选择需要复检的布料
                            MessageBox.Show("请选择需要复检的布料", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            var fm = new 库存选择() { StockName = danju.ckmc, CustomerName = danju.ksmc, Danhao = danju.dh };
                            fm.ShowDialog();
                            foreach (var s in fm.pingzhong)
                            {
                                Connect.dbcontext.Deleteable<JuanHaoTable>().Where (x => x.Ckmc == s.ID.ToString()).ExecuteCommand ();
                            }
                            //
                            dt = Connect.dbcontext.Ado.SqlQuery<JuanHaoTable>($"select * from juanhaotable where ckmc in (select convert(nvarchar(200),id) from stocktable where rkdh='{danju.dh}' and ms='0')");
                            if (dt.Count > 0)
                            {
                                foreach (string juan in dt.Select(x => x.Ckmc).Distinct())
                                {
                                    Sunny.UI.UIMessageBox.ShowAsk($"检测之前的入库信息已经有检验好的布料。但是这次没有该信息了！请重新关联\r\n" +
                                        $"缸号是'{dt.First(x => x.Ckmc == juan).GangHao }'\r\n" +
                                        $"品名是'{dt.First(x => x.Ckmc == juan).SampleName  }'\r\n" +
                                        $"颜色是'{dt.First(x => x.Ckmc == juan).yanse   }'\r\n" +
                                        $"款号是'{dt.First(x => x.Ckmc == juan).kuanhao   }'\r\n" +
                                        $"订单号是'{dt.First(x => x.Ckmc == juan).OrderNum   }'\r\n" +
                                        $"门幅是'{dt.First(x => x.Ckmc == juan).Menfu   }'\r\n" +
                                        $"克重是'{dt.First(x => x.Ckmc == juan).Kezhong   }'\r\n" +
                                        $"");
                                    fm = new 库存选择() { StockName = danju.ckmc, CustomerName = danju.ksmc, Danhao = danju.dh };
                                    fm.ShowDialog();
                                    if (fm.pingzhong.Count > 0)
                                    {
                                        Connect.dbcontext.Updateable<JuanHaoTable >().SetColumns(x=>x.Ckmc ==$"'{ fm.pingzhong[0].ID.ToString()}'").Where ( x => x.Ckmc == juan).ExecuteCommand ();
                                    }
                                }
                            }
                        }
                    }
                    Connect.dbcontext.Deleteable<StockTable>().Where (x => x.RKDH == danju.dh && x.MS == 0).ExecuteCommand ();
                }
                Connect.dbcontext.Deleteable<WarehousingDetailCode>(x => x.DocNum == txtdanhao.Text).ExecuteCommand();
                Connect.dbcontext.Insertable(detaicodelist).ExecuteCommand();
               // Connect.dbcontext.CommitTran();
                if (Sunny.UI.UIMessageBox.ShowAsk("是否直接开生产流转卡？\r\n直接开按确定。否则按取消"))
                {
                    MainForm.mainform.AddMidForm(new 流转卡() { danjumingxis = Connect.dbcontext.Queryable<danjumingxitable>().Where(x=>x.danhao==txtdanhao.Text ).ToList(), Useful = FormUseful.复制, danju = new DanjuTable() { ksmc = txtkehu.Text, ksbh = danju.ksbh, ckmc = txtckmc.Text, bz = txtbeizhu.Text, jiagongleixing = cmbJincangyuanying.Text } });
                }
                Useful = FormUseful.新增;
                Init();
            }
            catch (Exception ex)
            {
               // Connect.dbcontext.RollbackTran();
                ShowMessageBox.ShowErrorBox (  "保存单据的时候发生了错误" + ex.Message);
                return;
            }
        }
        private void txtkehu_ButtonCustomClick(object sender, EventArgs e)
        {
            var fm = new 客户选择();
            fm.ShowDialog();
            if(fm.linkman !=null)
            {
                danju.ksbh   = fm.linkman.BH ;
                txtkehu.Text = fm.linkman.MC ;
                if(!string.IsNullOrWhiteSpace (fm.linkman.bz))
                {
                    Sunny.UI.UIMessageBox.Show("该客户有特殊需求！\r\n需求是:"+fm.linkman.bz );
                }
            }
        }

        private void 复制行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rowindex = gridView1.FocusedRowHandle;
        }

        private void 粘贴行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CopyRow.Copy<danjumingxitable>(danjumingxis , rowindex, gridView1, gridView1.FocusedRowHandle,this);
        }

        private void 删除行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.DeleteRow(gridView1.FocusedRowHandle);
        }

        private void 添加行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            danjumingxis .Add(new danjumingxitable() { danhao = txtdanhao.Text, rq = uiDatePicker1.Value  });
            gridControl1.RefreshDataSource();
        }

        private void 配置列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView1) { formname = this.Name, Obj = new danjumingxitable() };
            fm.ShowDialog();
        }

        private void 保存样式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView1);
        }

        private void txtckmc_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            var fm = new 仓库选择();
            fm.ShowDialog();
            txtckmc.Text = fm.stock.mingcheng;
        }

        private void ButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (gridView1.FocusedRowHandle >= 0)
            {
                var fm = new 品种选择();
                fm.ShowDialog();
                var i = gridView1.FocusedRowHandle;
                foreach (var pingzhong in fm.pingzhong)
                {
                    danjumingxis[i].bizhong = "人民币￥";
                    danjumingxis[i].Bianhao = pingzhong.bh;
                    danjumingxis[i].guige = pingzhong.gg;
                    danjumingxis[i].chengfeng = pingzhong.cf;
                    danjumingxis[i].pingming = pingzhong.pm;
                    danjumingxis[i].kezhong = pingzhong.kz;
                    danjumingxis[i].menfu = pingzhong.mf;
                    danjumingxis[i].danwei = "米";
                    i++;
                    if (i == danjumingxis.Count - 1)
                        for (int j = 0; j < 30; j++)
                        {
                            danjumingxis.Add(new danjumingxitable() { danhao = txtdanhao.Text, rq = Convert.ToDateTime(uiDatePicker1.Text) });
                        }
                }
                fm.Dispose();
                gridControl1.RefreshDataSource();
                gridView1.CloseEditor();
            }
        }

        private void 选择工艺ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 工序选择();
            fm.ShowDialog();
            foreach (var t in fm.technologyTables )
            {
                txtbeizhu.Text += t.Technology + "+";
            }
            if(txtbeizhu.Text .Length >0)
            txtbeizhu.Text = txtbeizhu.Text.Substring(0, txtbeizhu.Text.Length - 1);
        }

        private void 复制单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridControl1.Focus();
            SendKeys.Send("^c");
        }

        private void 粘贴单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridControl1.Focus();
            SendKeys.Send("^v");
        }

        private void txtkehu_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Enter )
            {
                var fm = new 客户选择();
                fm.linkman.ZJC = txtkehu.Text;
                fm.linkman.MC = string.Empty;
                fm.ShowDialog();
                if (fm.linkman != null)
                {
                    danju.ksbh = fm.linkman.BH;
                    txtkehu.Text = fm.linkman.MC;
                }
            }
        }

        private void txtckmc_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode==Keys.Enter )
            {
                var fm = new 仓库选择() {stock=new StockInfoTable { Zhujici=txtckmc.Text } };
                fm.ShowDialog();
                txtckmc.Text = fm.stock.mingcheng;
            }
        }

        private void 相同品名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var pingming = gridView1.GetRowCellValue(gridView1.GetSelectedRows()[0], "pingming").ToString();
            foreach (var row in gridView1.GetSelectedRows ())
            { 
                gridView1.SetRowCellValue (row,"pingming" , pingming);
            }
        }

        private void 相同颜色ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var yanse = gridView1.GetRowCellValue(gridView1.GetSelectedRows()[0], "yanse").ToString();
            foreach (var row in gridView1.GetSelectedRows())
            {
                gridView1.SetRowCellValue(row, "yanse", yanse );
            }
        }

        private void txtckmc_ButtonClick(object sender, EventArgs e)
        {
            var fm = new 仓库选择() { stock = new StockInfoTable { Zhujici = txtckmc.Text } };
            fm.ShowDialog();
            txtckmc.Text = fm.stock.mingcheng;
        }

        private void 来货入库单_Load(object sender, EventArgs e)
        {
            Init();
        }

        private void 输入细码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (detaicodelist.Count == 0)
            {
                var fm = new 输入来货细码()
                {
                    useful = FormUseful.新增,
                    dt = FineCodeTable,
                    mingxilist = danjumingxis.Where(x => x.pingming != null).ToList() 
                };
                fm.ShowDialog();
            }
            else
            {
                FineCodeTable = new DataTable();
               
                foreach (var col in detaicodelist.Select (x=>x.LotNum ).Distinct ())
                { 
                    int rowindex = 0;
                    FineCodeTable.Columns.Add(col);
                   foreach(var d in detaicodelist.Where(x => x.LotNum == col).ToList())
                    {
                        if (rowindex == FineCodeTable.Rows.Count)
                        {
                            FineCodeTable.Rows.Add();                           
                        }
                        FineCodeTable.Rows[rowindex][col] = d.Length; 
                        rowindex++;
                    }
                }               
                var fm = new 输入来货细码()
                {
                    useful = FormUseful.修改,
                    dt = FineCodeTable,
                    mingxilist = danjumingxis.Where(x => x.pingming != null).ToList()
                };
                fm.ShowDialog();
            }          
            detaicodelist.Clear();
            foreach(DataColumn col in FineCodeTable.Columns  )
            {
                foreach (DataRow row in FineCodeTable.Rows)
                {
                    detaicodelist.Add(new WarehousingDetailCode { DocNum = txtdanhao.Text, LotNum = col.ColumnName,Length =row[col]==null?string.Empty :row[col].ToString() });
                }
            }
            gridControl1.RefreshDataSource();
        }
    }
}
